// @Author：bishisimo 2021/4/30 上午10:44
// @Description：
package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"github.com/bishisimo/errlog"
	"io"
	"math/big"
	"os"
)

func GenerateTLSConfig() *tls.Config {
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}
	template := x509.Certificate{SerialNumber: big.NewInt(1)}
	certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
	if err != nil {
		panic(err)
	}
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})

	tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
	if err != nil {
		panic(err)
	}
	return &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
		NextProtos:   []string{"quic-echo-example"},
	}
}

func GetTLSConfig() *tls.Config  {
	cf,err:=os.Open("ssl/cert.pem")
	errlog.Debug(err)
	kf,err:=os.Open("ssl/key.pem")
	errlog.Debug(err)

	certPEM,err:=io.ReadAll(cf)
	errlog.Debug(err)
	keyPEM,err:=io.ReadAll(kf)
	errlog.Debug(err)

	tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
	errlog.Debug(err)
	if err != nil {
		return nil
	}
	return &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
		NextProtos:   []string{"all"},
	}
}